"""Record Array Parameter
.. helpdoc::
This widget records parameters from an array into a table, which could then be copied or saved into another file for analysis.  The widget takes a NumpyArray and optionally a parent array from which to extract data about the orriginal array, such as file name, etc."""

"""
<widgetXML>    
    <name>Record Array Parameter</name>
    <icon>default.png</icon>
    <tags> 
        <tag>Matplotlib Plotting</tag> 
    </tags>
    <summary>Recoerd Array parameters.</summary>
    <author>
        <authorname>Kyle R. Covington</authorname>
        <authorcontact>kyle@red-r.org</authorcontact>
    </author>
</widgetXML>
"""
from OWRpy import * 
import redRGUI, signals 
import numpy, scipy, pylab

import redRi18n, globalData
_ = redRi18n.get_(package = 'base')
class arrayParameter(OWRpy):
    def __init__(self, **kwargs):
        OWRpy.__init__(self, **kwargs)
        self.setRvariableNames(['arrayData'])
        self.image1 = None
        self.image2 = None
        
        """.. rrsignals::"""
        self.inputs.addInput('id1', _('Image 1'), signals.base.NumpyArray, self.processImage1)
        
        """.. rrsignals::"""
        self.outputs.addOutput('rdata', "Data Table", signals.base.RDataFrame)
        
        
        box = redRGUI.base.widgetBox(self.controlArea, orientation = 'horizontal')
        
        self.GUI_outputArea = redRGUI.base.textEdit(self.controlArea, label = "Output")
        self.GUI_outputArea.insertPlainText("FileName; Shape; Area; Sum; Average\n")
    def processImage1(self, data):
        if data:
            self.image1 = data.getData()
            self.commitFunction()
        else:
            self.image1 = None
    
    def commitFunction(self):
        if self.image1 == None: return
        output = []
        if globalData.globalDataExists("ImageFileName"):
            gd = globalData.getGlobalData("ImageFileName")
            if len(gd) == 1:
                output.append(gd[0]['data'])
            else:
                output.append(','.join(x['data'] for x in gd))
        else: output.append("NA")
        output.append(str(self.image1.shape))
        output.append(str(self.image1.shape[0]*self.image1.shape[1]))
        output.append(str(self.image1.sum()))
        #output.append(str(self.image1.minimum()))
        #output.append(str(self.image1.maximum()))
        output.append(str(self.image1.mean()))
        self.GUI_outputArea.insertPlainText('%s\n' % '; '.join(output))
        
    def toRDataFrame(self):
        """Generates an R dataframe from the text data."""
        text = unicode(self.GUI_outputArea.toPlainText())
        lines = text.split("\n")
        FileName = []
        Shape = []
        Area = []
        Sum = []
        Average = []
        for l in lines[1:]:
            ld = l.split(';')
            FileName.append(ld[0].strip())
            Shape.append(ld[1].strip())
            Area.append(ld[2].strip())
            Sum.append(ld[3].strip())
            Average.append(ld[4].strip())
            
        self.R('%(data)s<-data.frame(FileName = %(FileName)s, Shape = %(Shape)s, Area = %(Area)s, Sum = %(Sum)s, Average = %(Average)s)' % {'data':self.Rvariables['arrayData'], 'FileName': 'c("%s")' % '","'.join(FileName), 'Shape': 'c("%s")' % '","'.join(Shape), 'Area': 'c(%s)' % ','.join(Area), 'Sum': 'c(%s)' % ','.join(Sum), 'Average': 'c(%s)' % ','.join(Average)}, wantType = redR.NOCONVERSION)
        
        